package com.monlyu.bo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.monlyu.bean.Page;
import com.monlyu.bean.Pages;
import com.monlyu.bean.UserTree;
import com.monlyu.model.TmpUser;
import com.monlyu.util.LogUtil;
import com.monlyu.util.PermissUtil;
import com.monlyu.util.SecurityUtil;
import com.monlyu.util.StringUtil;
import com.monlyu.util.WebOptUtil;
import com.monlyu.vo.Role;
import com.monlyu.vo.User;
import com.monlyu.vo.User2Role;

/*******************************************************************************
 * <b>功能描述☞</b>操作系统用户的类<br>
 * <b>开发公司☞</b>重庆唯尼科技有限公司<br>
 * <b>版权☞</b>本文件归重庆唯尼科技有限公司所有<br>
 * <b>项目名☞</b>monlyu<br>
 * <b>文件路径☞</b>com.monlyu.action.user.EditUserAction.java<br>
 * <b>开发日期☞</b>2010-1-14 <br>
 * 
 * @author monlyu
 * @since JDK 5
 * @version 1.0.5
 ******************************************************************************/
@Repository(value = "userBo")
public class UserBo extends BaseBo {

	private EnumsBo enumsBo;

	public void setEnumsBo(EnumsBo enumsBo) {
		this.enumsBo = enumsBo;
	}

	public User findUser(User user) {
		Criteria criteria = dao.initCriteria(User.class);
		criteria.add(Restrictions.eq("nickName", user.getNickName()));
		// 这个放到action中去验证，便于提示
		// criteria.add(Restrictions.eq("enable", true));
		return criteria.list().isEmpty() ? null : (User) criteria.list().get(0);
	}

	/** 加载用户信息 */
	public void load(User user) {
		dao.load(user);
	}

	/**
	 * 保存到数据库中
	 * 
	 * @author monlyu
	 * @since 2010-1-17
	 */
	public void save(User user, Long[] roles) {
		if (user.getId() == null) {
			user.setPasswd(SecurityUtil.md5(user.getPasswd()));
		}
		dao.insertOrUpdate(user);
		PermissUtil.clearCache(user.getId());// 清空缓存
		dao.execute("delete from com.monlyu.vo.User2Role u where u.userId=?",
				user.getId());
		if (roles != null) {
			for (Long newLong : roles) {
				User2Role user2Role = new User2Role();
				user2Role.setRoleId(newLong);
				user2Role.setUserId(user.getId());
				dao.save2key(user2Role);
			}
		}
	}

	// 保存角色信息
	public void saveRole2User(Long userId, Long[] roles) {
		PermissUtil.clearCache(userId);// 清空缓存
		dao.execute("delete from com.monlyu.vo.User2Role u where u.userId=?",
				userId);
		if (roles != null) {
			for (Long newLong : roles) {
				User2Role user2Role = new User2Role();
				user2Role.setRoleId(newLong);
				user2Role.setUserId(userId);
				dao.save2key(user2Role);
			}
		}
	}

	/**
	 * 查询所有的用户信息
	 * 
	 * @author monlyu
	 * @param page
	 *            字段设置
	 * @since 2010-2-3
	 */
	public Pages<User> findAllUser(Page page, boolean status) {
		Criteria criteria = dao.initCriteria(User.class);
		criteria.add(Restrictions.eq("enable", status));
		return buildPages(page, criteria, "name", "nickName", "telel", "email");
	}

	/**
	 * 修改用户密码
	 * 
	 * @author monlyu
	 * @since 2010-2-3
	 * @param user
	 *            用户
	 * @param oripwd
	 *            原始密码
	 * @param focus
	 *            强制修改密码
	 */
	public String repwd(User user, String oripwd, boolean focus) {
		if (!focus) {
			if (!SecurityUtil.md5(oripwd).equals(curUser().getPasswd())) {
				return "原始密码输入错误";
			}
		}
		final String hql = "update com.monlyu.vo.User u set u.passwd=? where u.id=?";
		dao.execute(hql, SecurityUtil.md5(user.getPasswd()), user.getId());
		return "";
	}

	/**
	 * 获取所有的用户
	 * 
	 * @author monlyu
	 * @since 2010-2-4
	 */
	public List<User> loadAllUser() {
		return dao.find(User.class);
	}

	public Pages<User> searchUser(User user, Page page) {
		Criteria criteria = dao.initCriteria(User.class);
		if (user != null && !StringUtil.isEmpty(user.getName())) {
			criteria.add(Restrictions.like("name", user.getName().trim(),
					MatchMode.ANYWHERE));
		}
		if (user != null && user.getDept() != null
				&& user.getDept().intValue() != 0) {
			criteria.add(Restrictions.eq("dept", Long.valueOf(user.getDept())));
		}
		if (user != null && user.getRole() != null
				&& user.getRole().getId() != null) {
			criteria.add(Restrictions.in("id", getUserIds(user.getRole()
					.getId())));
		}
		criteria.addOrder(Order.asc("name"));
		Pages<User> users = buildPages(page, criteria);
		if (users.list() == null) {
			return users;
		}
		return setRole(users);
	}

	private Pages<User> setRole(Pages<User> users) {
		List<User> userList = new ArrayList<User>();
		for (User user : users.getItems()) {
			user.setRole(getRoleByUserId(user.getId()));
			userList.add(user);
		}
		users.setItems(userList);
		return users;
	}

	private Role getRoleByUserId(Long id) {
		Long roleId = (Long) dao
				.findOne(
						"select roleId from com.monlyu.vo.User2Role where userId=?",
						id);
		if (roleId == null) {
			return null;
		}
		return dao.get(Role.class, roleId);
	}

	@SuppressWarnings("unchecked")
	private List<Long> getUserIds(Long id) {
		String hql = "select userId from com.monlyu.vo.User2Role where roleId=?";
		return dao.find(hql, id);
	}

	@SuppressWarnings("unchecked")
	public Map<Long, UserTree> buildTree() {
		Criteria criteria = dao.initCriteria(User.class);
		criteria.addOrder(Order.asc("dept"));
		List<User> all = criteria.list();
		Map<Long, UserTree> trees = Maps.newHashMap();
		for (User user : all) {
			UserTree tmp = trees.get(user.getDept());
			if (tmp == null) {
				Object val = enumsBo.getEnumValue(user.getDept());
				UserTree tre = new UserTree();
				tre.setDept(val.toString());
				tre.addUser(user);
				trees.put(user.getDept(), tre);
			} else {
				tmp.addUser(user);
			}
		}
		return trees;
	}

	/**
	 * 根据字符串获取人员,如: 3,4,5,6,5
	 */
	public List<User> findUser(String user) {
		List<User> uList = Lists.newArrayList();
		if ((!StringUtil.isEmpty(user))) {
			String[] list = user.split(",");
			for (String string : list) {
				try {
					Long id = Long.parseLong(string);
					if (id != null) {
						uList.add(dao.get(User.class, id));
					}
				} catch (Exception e) {
					LogUtil.log(getClass()).info("没找到对应ID的用户" + string);
					continue;
				}
			}
		}
		return uList;
	}

	/**
	 * 根据用户的角色来查询用户
	 * 
	 * @param role
	 *            角色字符串
	 * @return List 返回选择的用户列
	 */
	@SuppressWarnings("unchecked")
	public List<User> getUser(String role) {
		if (!StringUtil.isEmpty(role)) {
			List<User> users = null;// ROLE_USER_CACHE.get(role);
			if (users == null) {
				Role myrole = dao.findOne(Role.class, "name", role);
				if (myrole == null) {
					return Collections.EMPTY_LIST;
				} else {
					Role derole = dao.findOne(Role.class, "name", role);
					if (derole != null) {
						Criteria criteria = dao.initCriteria(User.class);
						List<Long> rids = dao
								.find(
										"select distinct(t.userId) from User2Role t where t.roleId=?",
										derole.getId());
						if (!rids.isEmpty()) {
							criteria.add(Restrictions.in("id", rids));
							return criteria.list();
						}
					}
				}
			}
		}
		return loadAllUser();
	}

	/** 查找所有的人员 */
	@SuppressWarnings("unchecked")
	public List<User> findUsers() {
		Criteria criteria = dao.initCriteria(User.class);
		criteria.add(Restrictions.not(Restrictions.eq("id", 1L)));
		criteria.add(Restrictions.eq("enable", true));
		criteria.addOrder(Order.asc("name"));
		return criteria.list();
	}

	/**
	 * 获取当前用户的信息
	 */
	public User load() {
		return dao.get(User.class, curUser().getId());
	}

	public TmpUser getRemoteUser(User dbUser) {
		String sql = String
				.format(
						"select %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s from %s where ID='%s'",
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.username"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.man"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.mail"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.homeAddr"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.homeTel"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.workTel"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.idNum"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.hire"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.birth"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.jinji"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.jinjiTel"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user.qq"),
						WebOptUtil.ALL_SYSTEM_PROPERY.get("user"));
		List<?> all = dao.getSqlDao().find(sql, 1);
		Object obj = all.get(0);
		return (TmpUser) obj;
	}

	/**
	 * 根据权限查询用户列表
	 * 
	 * @param permissionId
	 * @return
	 * @since chendan 2011-7-26
	 */
	public List<User> getUserByPermission(String permissionId) {
		String hql = "select u from com.monlyu.vo.Role2Permission rp,com.monlyu.vo.User2Role ur,"
				+ "com.monlyu.vo.User u where rp.roleId=ur.roleId and ur.userId=u.id "
				+ "and rp.permissionId =? order by u.name";
		return dao.find(hql, permissionId);
	}
}
